// API服务处理
import { openaiClient } from '../lib/openai/client';
import { ChatHistory } from '../lib/chat/history';
import { printStream } from '../lib/chat/utils';
import { config } from '../config';
import { cli } from '../lib/interface/cli-manager';

export class ApiService {
  constructor(private readonly history: ChatHistory) {}
  private readonly cli = cli;
  async getAIResponse(): Promise<void> {
    try {
      // 进入响应状态前处理提示符
      this.cli.hidePrompt();
      this.cli.writeOutput('\n🤖 '); // 新行开始输出

      const stream = await openaiClient.chat.completions.create({
        model: config.MODEL,
        messages: this.history.getMessages(),
        stream: true
      });

      let fullResponse = '';
      let isFirstChunk = true;
      let isThinking = false; // 正在思考
      for await (const chunk of stream) {
        if (isFirstChunk) {
          this.cli.writeOutput('\x1B[s'); // 保存光标位置
          isFirstChunk = false;
        }
        const delta = chunk.choices[0]?.delta;
        //@ts-ignore
        const reasoning_content = delta?.reasoning_content
        if(reasoning_content) { // 如果有思考过程先处理这个
          if(!isThinking) {
            isThinking = true;
            printStream(`${'='.repeat(6)}思考过程${'='.repeat(6)}`, 'thinking')
          }
          printStream(reasoning_content, 'thinking')
        }
        else {
          if(isThinking) { // 由思考结束转为回答时，需要一个换行
            printStream(`\n${'='.repeat(5)}思考结果${'='.repeat(5)}`, 'answer')
          }
          isThinking = false; // 思考结束
          const content = delta?.content || '';
          fullResponse += content;
          printStream(content, 'answer');
        }
      }

      this.cli.writeOutput('\x1B[u\n'); // 恢复光标并换行
      this.cli.interface.resume();
      this.cli.showPrompt();

      if (fullResponse) {
        this.history.add({ role: 'assistant', content: fullResponse });
      }

    } catch (error) {
      this.history.getMessages().pop();
      throw error;
    }
  }
}
